package com.cygsunri.commonbase.exception;

import com.cygsunri.commonutils.exception.ExceptionUtil;
import com.cygsunri.commonutils.response.ResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author hanyuanLiu
 * @site USER_M
 * @company 统一异常处理类
 * @create 2021-03-29 17:50
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultWrapper<Object> error(Exception e){
        e.printStackTrace();
        log.error(ExceptionUtil.getMessage(e));
        return ResultWrapper.error("执行了全局异常");
    }

    /**
     * 指定异常
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResultWrapper<Object> error(NullPointerException e){
        e.printStackTrace();
        log.error(ExceptionUtil.getMessage(e));
        return ResultWrapper.error("执行了指定异常==》NullPointerException");
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResultWrapper<Object> error(CustomException e){
        e.printStackTrace();
        log.error(ExceptionUtil.getMessage(e));
        return ResultWrapper.error(e.getCode(),e.getMsg());
    }
}
